#!/bin/bash
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

. "$(dirname "$0")/common.sh" || exit 1

# Script must run inside the chroot
assert_inside_chroot "$@"

# Do not run as root
assert_not_root_user

FLAGS_HELP="usage: $(basename $0) [flags]
Updates the host python and associated packages. This script is called as part
of build_packages, so there is typically no need to call this script directly.
"
show_help_if_requested "$@"

# The following options are advanced options, only available to those willing
# to read the source code. They are not shown in help output, since they are
# not needed for the typical developer workflow.
DEFINE_integer jobs -1 \
  "How many packages to build in parallel at maximum."

# Parse command line flags
FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"

# Only now can we die on error.  shflags functions leak non-zero error codes,
# so will die prematurely if 'switch_to_strict_mode' is specified before now.
switch_to_strict_mode

CHROMITE_BIN="${GCLIENT_ROOT}/chromite/bin"
EMERGE_CMD="${CHROMITE_BIN}/parallel_emerge"

do_cleanup=${FLAGS_FALSE}
cmds=()

# If we've got multiple versions of python installed, clear them out.
PYTHON_VERSIONS=( $(qlist -ICv -e dev-lang/python | sort -nr) )
if [[ ${#PYTHON_VERSIONS[@]} -gt 1 ]]; then
  info "Cleaning up system python"
  cmds+=(
    # Make sure we have the latest version selected.
    'eselect python update'
    # Unmerge all the older versions.
    "CLEAN_DELAY=0 emerge -Cq ${PYTHON_VERSIONS[*]:1}"
  )
  do_cleanup=${FLAGS_TRUE}
fi

# If the user still has old python modules installed, update them.
PYTHON_VERSIONS=(
  # Filter out the new python-exec package.
  $(ls -d /usr/lib*/python*/ | cut -d/ -f4 | grep -v python-exec | sort -uV)
)
if [[ ${#PYTHON_VERSIONS[@]} -gt 1 ]]; then
  PY_UPDATE_FLAGS=()
  if [[ ${FLAGS_jobs} -ne -1 ]]; then
    PY_UPDATE_FLAGS+=( --jobs=${FLAGS_jobs} )
  fi
  cmds+=(
    "python-updater --package-manager-command ${EMERGE_CMD} -- \
      ${PY_UPDATE_FLAGS[*]}"
  )

  # python-updater does not handle /usr/local, so do it ourselves.
  # We have to run this after python-updater though since these packages
  # might rely on other dev-python stuff in /usr.
  pkgs=( $(qfile -qC /usr/local/lib*/python* | sort -u) )
  if [[ ${#pkgs[@]} -gt 0 ]]; then
    cmds+=( "${EMERGE_CMD} ${PY_UPDATE_FLAGS[*]} ${pkgs[*]}" )
  fi
  old_py_dir=${PYTHON_VERSIONS[0]}
  do_cleanup=${FLAGS_TRUE}
else
  old_py_dir=
fi

if [[ ${do_cleanup} -eq ${FLAGS_TRUE} ]]; then
  cmds+=(
    # Make sure chromite can be found.  We also clean up old chromite paths
    # that might have been accidentally created (make_chroot/etc...).
    'rm -f /usr/lib64/python*/{site-packages/,}chromite'
    'ln -sf /mnt/host/source/chromite \
      /usr/lib64/python$(eselect python show --ABI)/site-packages/chromite'
  )

  if [[ -n ${old_py_dir} ]]; then
    cmds+=(
      # Trim generated pyc files if they've been left behind.
      "find /usr/lib*/${old_py_dir}/ /usr/local/lib*/${old_py_dir}/ \
        -name '*.pyc' -delete 2>/dev/null || :"

      "find /usr/lib*/${old_py_dir}/ /usr/local/lib*/${old_py_dir}/ \
        -depth -type d -delete 2>/dev/null || :"
    )
  fi

  cmds+=(
    # Remove empty dirs if possible.
    'rmdir /usr/local/lib*/python*/site-packages /usr/local/lib*/python*/ \
      /usr/lib*/python*/site-packages /usr/lib*/python*/ 2>/dev/null || :'
  )
fi

sudo_multi "${cmds[@]}"
